import { TDate } from 'src/common/Date'
import { User } from 'src/user/entities/user.entity'
import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  Unique,
  BeforeInsert,
  BeforeUpdate,
  ManyToOne,
  JoinColumn
} from 'typeorm'

@Entity('operation')
@TDate()
export class Operation {
  @PrimaryGeneratedColumn()
  id: number

  @Column()
  @Unique('code', ['code'])
  code: string

  @Column()
  @Unique('name', ['name'])
  name: string

  @Column({ nullable: true })
  description: string

  @ManyToOne(() => User, (user) => user.id, { onDelete: 'SET NULL' })
  @JoinColumn({ name: 'created_by' })
  createdBy: number

  @ManyToOne(() => User, (user) => user.id, { onDelete: 'SET NULL' })
  @JoinColumn({ name: 'updated_by' })
  updatedBy: number

  constructor(operation?: Partial<Operation>) {
    Object.assign(this, operation)
  }

  @BeforeInsert()
  @BeforeUpdate()
  validateCode() {
    if (!/^[a-zA-Z]+$/.test(this.code)) {
      throw new Error('操作编码必须为英文字母')
    }
  }
}
